<template>
  <div class="main-content">
    <van-row>
      <van-col span="24" class="login-header">首页</van-col>
    </van-row>
    <!-- 开始年月 -->
    <van-cell is-link @click="showPopup" :value="value" class="body-content">
      <template #title>
        <span class="custom-title">请选择开始年月</span>
      </template>
    </van-cell>
    <van-popup
      class="popup-class"
      v-model="showPicker"
      round
      position="bottom"
      :style="{ height: '50%' }"
    >
      <!-- closeable -->
      <van-datetime-picker
        v-model="currentDate"
        type="year-month"
        title="选择年月"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="onConfirm()"
        @cancel="cancel()"
      />
    </van-popup>
    <!-- 结束年月 -->
    <van-cell is-link @click="showPopup2" :value="value2">
      <template #title>
        <span class="custom-title">请选择结束年月</span>
      </template>
    </van-cell>
    <van-popup
      class="popup-class"
      v-model="showPicker2"
      round
      position="bottom"
      :style="{ height: '50%' }"
    >
      <!-- closeable -->
      <van-datetime-picker
        v-model="currentDate2"
        type="year-month"
        title="选择年月"
        :min-date="currentDate"
        :max-date="maxDate"
        :formatter="formatter2"
        @confirm="onConfirm2()"
        @cancel="cancel2()"
      />
    </van-popup>
    <div class="order-content">
      <van-grid :column-num="3" :gutter="10" class="card-content">
        <van-grid-item @click="onQueryOrderByDate(1)">
          <p class="p-content">订单金额：</p>
          <p class="p-content">{{unitConvert(amount).num}}{{unitConvert(amount).unit}}</p>
        </van-grid-item>
        <van-grid-item @click="onQueryOrderByDate(2)">
          <p class="p-content">发货金额：</p>
          <p
            class="p-content"
          >{{unitConvert(deliveryAmount).num}}{{unitConvert(deliveryAmount).unit}}</p>
        </van-grid-item>
        <van-grid-item @click="onQueryOrderByDate(3)">
          <p class="p-content">收款金额：</p>
          <p
            class="p-content"
          >{{unitConvert(origSettleAmount).num}}{{unitConvert(origSettleAmount).unit}}</p>
        </van-grid-item>
        <van-grid-item v-if="isShow">
          <p class="p-content">成本金额：</p>
          <p class="p-content">{{unitConvert(costAmount).num}}{{unitConvert(costAmount).unit}}</p>
        </van-grid-item>
        <van-grid-item v-if="isShow">
          <p class="p-content">毛利润：</p>
          <p class="p-content">{{unitConvert(profit).num}}{{unitConvert(profit).unit}}</p>
        </van-grid-item>
      </van-grid>
    </div>

    <div ref="saleData" class="sale-content">
      <!-- <h6>销售走势</h6>
      <img src="../../static/img/stLogo.png" alt />-->
    </div>
    <!-- <div v-show="false">
      <indexPage ref="indexPage" />
    </div>-->
  </div>
</template>
<script>
import indexPage from "@/components/index";
import { queryData, findMoneyByCustomer } from "@/api/main/main";
import { exitSystem } from "@/api/public/public";
export default {
  // components: {
  //   indexPage,
  // },
  data() {
    return {
      // 用户数据
      user: "",
      // 下拉
      activeNames: [],
      // 开始年月
      value: "",
      tempValue: "",
      showPicker: false,
      // 业务员身份判断
      isShow: "",
      minDate: new Date(2010, 0, 1),
      maxDate: new Date(2050, 11, 1),
      currentDate: new Date(),
      // 结束年月
      show2: false,
      value2: "",
      showPicker2: false,
      minDate2: new Date(2010, 0, 1),
      maxDate2: new Date(2050, 11, 1),
      currentDate2: new Date(),
      // 首页数据源
      mainData: [],
      // 总金额、利润等数据
      years: [], //年月数据
      money: [], //订单金额数据
      deliveryAmountArr: [], //发货金额数据
      origSettleAmountArr: [], //收款金额数据
      amount: 0, //订单金额
      deliveryAmount: 0, // 发货金额
      origSettleAmount: 0, // 收款金额
      costAmount: 0, //成本金额
      profit: 0, //  毛利润
      // 业务员id
      idclerk: "",
    };
  },
  created() {
    //   // 业务员id
    let person = this.$session.get("person");
    this.idclerk = JSON.parse(person).personId;
    // 获取最近6个月的数据;
    this.getSixMonth();
    // 获取首页订单数据
    this.getMainData();
  },
  mounted() {
    // this.$nextTick(() => {
    //   // echarts图表
    //   this.getSaleData();
    // });
    // 业务员身份判断
    this.user = JSON.parse(this.$session.get("user"));
    console.log("user", this.user);
    let saleType = this.user.saleType;
    // saleType(0为业务员1为主管)
    saleType === 0 ? (this.isShow = false) : (this.isShow = true);
    // // 返回按钮事件监听
    // // 如果支持 popstate 一般移动端都支持了
    // if (window.history && window.history.pushState) {
    //   // 往历史记录里面添加一条新的当前页面的url
    //   history.pushState(null, null, document.URL);
    //   // 给 popstate 绑定一个方法 监听页面刷新
    //   window.addEventListener("popstate", this.backChange, false); //false阻止默认事件
    // }
  },
  destroyed() {
    // window.removeEventListener("popstate",  this.backChange, false); //false阻止默认事件
  },
  methods: {
    // // 返回按钮事件
    // backChange(){
    //   exitSystem();
    // },
    // 点击订单金额查询范围内的订单
    onQueryOrderByDate(status) {
      // this.$emit("fatherMethod");
      // this.$refs.indexPage.updateActive("searchPage");
      let condition = {
        mainPage: true,
        startTime: `${this.value}/01`,
        endTime: `${this.value2}/01`,
        idclerk: this.idclerk,
      };
      this.$session.set("mainPageCondition", condition);
      this.$router.push({
        name: "customerPage",
        query: {
          startTime: `${this.value}/01`,
          endTime: `${this.value2}/01`,
          idclerk: this.idclerk,
          status: status,
        },
      });
    },
    // 单位转换
    unitConvert(num) {
      // console.log("num",num);
      var moneyUnits = ["元", "万元", "亿元", "万亿"];
      var dividend = 10000;
      var curentNum = num;
      //转换数字
      var curentUnit = moneyUnits[0];
      //转换单位
      for (var i = 0; i < 4; i++) {
        curentUnit = moneyUnits[i];
        if (this.strNumSize(curentNum) < 5) {
          break;
        }
        curentNum = curentNum / dividend;
      }
      var m = { num: 0, unit: "" };
      m.num = curentNum.toFixed(2);
      m.unit = curentUnit;
      return m;
    },
    strNumSize(tempNum) {
      var stringNum = tempNum.toString();
      var index = stringNum.indexOf(".");
      var newNum = stringNum;
      if (index != -1) {
        newNum = stringNum.substring(0, index);
      }
      return newNum.length;
    },
    // 获取最近六个月的日期
    getSixMonth() {
      //创建现在的时间
      var data = new Date();
      //获取年
      var year = data.getFullYear();
      //获取月
      var mon = data.getMonth() + 1;
      var arry = new Array();
      for (var i = 0; i < 6; i++) {
        mon = mon - 1;
        if (mon <= 0) {
          year = year - 1;
          mon = mon + 12;
        }
        if (mon < 10) {
          mon = "0" + mon;
        }
        arry[i] = year + "/" + mon;
      }
      // 起止时间
      this.value2 = arry[0];
      this.value = arry[5];
      return arry;
    },
    // 获取首页数据
    getMainData() {
      this.years = [];
      this.money = [];
      this.mainData = [];
      this.deliveryAmountArr = [];
      this.origSettleAmountArr = [];
      this.amount = 0;
      this.deliveryAmount = 0;
      this.origSettleAmount = 0;
      this.costAmount = 0;
      this.profit = 0;

      // 获取账套下的数据库
      let DsName = this.$session.get("DsName");
      let user = JSON.parse(this.$session.get("user"));
      console.log("this.user", user);
      console.log("this.user.appBs", user.appBs);

      let condition = {
        DsName: JSON.parse(DsName),
        idclerk: this.idclerk,
        startTime: `${this.value}/01`,
        endTime: `${this.value2}/01`,
        appBs: user.appBs,
      };
      queryData(condition, (data) => {
        this.mainData = data.data;
        this.mainData.forEach((ele) => {
          // 总金额、利润等等
          // echarts x轴数据 日期
          this.years.push(ele.years);
          if (ele.amount) {
            // echarts y轴数据 订单金额
            this.money.push(ele.amount);
            this.amount += ele.amount;
          }
          if (ele.deliveryAmount) {
            // echarts y轴数据 发货金额
            this.deliveryAmountArr.push(ele.deliveryAmount);
            this.deliveryAmount += ele.deliveryAmount;
          }
          if (ele.origSettleAmount) {
            // echarts y轴数据 收款金额
            this.origSettleAmountArr.push(ele.origSettleAmount);
            this.origSettleAmount += ele.origSettleAmount;
          }
          if (ele.costAmount) {
            this.costAmount += ele.costAmount;
          }
          if (ele.profit) {
            this.profit += ele.profit;
          }
        });

        // 渲染echarts图表
        this.getSaleData();
      });
    },
    // echarts图表单位转化
    getSaleData() {
      // 将元转化为万元
      let ded = 10000;
      // let money=[1,2,3,4,5,6,7,8]
      // 订单金额
      let money = this.money.map((ele) => {
        ele = (ele / ded).toFixed(2);
        return ele;
      });
      // 发货金额
      let deliveryAmountArr = this.deliveryAmountArr.map((ele) => {
        ele = (ele / ded).toFixed(2);
        return ele;
      });
      // 收款金额
      let origSettleAmountArr = this.origSettleAmountArr.map((ele) => {
        ele = (ele / ded).toFixed(2);
        return ele;
      });
      // 生成图表
      let saleChat = this.$echarts.init(this.$refs.saleData);
      saleChat.setOption({
        title: {
          text: "",
        },
        tooltip: {},
        legend: {
          data: ["订单", "发货", "收款"],
        },
        gird: {
          // 解决y轴太宽显示不全
          // containLabel: true,
          // left: "30%",
          // x:200,
          // y:50,
          // y2:50,
          // x2:50,
        },
        xAxis: {
          name: "时间",
          data: this.years,
          // data: ["1","2","3",""]
        },
        yAxis: {
          name: "万元",
          // max: 10000,
          // min: 0
        },
        series: [
          {
            name: "订单",
            type: "line",
            smooth: true, //true就是曲线，false就是折线，默认false
            data: money,
          },
          {
            name: "发货",
            type: "line",
            smooth: true, //true就是曲线，false就是折线，默认false
            data: deliveryAmountArr,
          },
          {
            name: "收款",
            type: "line",
            smooth: true, //true就是曲线，false就是折线，默认false
            data: origSettleAmountArr,
          },
        ],
      });
    },
    // 补0函数
    Appendzero(obj) {
      if (obj < 10) return "0" + "" + obj;
      else return obj;
    },
    // 开始年月选择
    onConfirm(date) {
      this.value = `${this.currentDate.getFullYear()}/${this.Appendzero(
        this.currentDate.getMonth() + 1
      )}`;
      this.showPicker = false;
      // this.tempValue = date;
      // this.value = this.currentDate;
      this.getMainData();
    },
    showPopup() {
      this.showPicker = true;
    },
    cancel() {
      this.showPicker = false;
    },
    // 结束年月选择
    onConfirm2(date) {
      this.value2 = `${this.currentDate2.getFullYear()}/${this.Appendzero(
        this.currentDate2.getMonth() + 1
      )}`;
      // /${date.getDate()}
      this.showPicker2 = false;
      // this.value2 = this.currentDate2;
      this.getMainData();
    },
    showPopup2() {
      this.showPicker2 = true;
    },
    cancel2() {
      this.showPicker2 = false;
    },
    //   开始年月
    formatter(type, val) {
      if (type === "year") {
        return `${val}`;
      } else if (type === "month") {
        return `${val}`;
      }
      return val;
    },
    //   结束年月
    formatter2(type, val) {
      if (type === "year") {
        return `${val}`;
      } else if (type === "month") {
        return `${val}`;
      }
      return val;
    },
  },
};
</script>
<style lang="scss" scoped>
.main-content {
  .login-header {
    height: 60px;
    width: 100%;
    color: white;
    line-height: 60px;
    background-color: #1989fa;
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 1;
  }
  .body-content {
    margin-top: 60px;
  }
  .custom-title {
    float: left;
  }
  .order-content {
    margin-top: 10px;
    .card-content {
      margin-top: 5px;
      .p-content {
        margin: 0px;
      }
    }
    .date-content {
      text-align: left;
      margin-left: 10px;
    }
  }
  .sale-content {
    margin-top: 10px;
    margin-bottom: 60px;
    width: 100%;
    height: 300px;
  }
}
</style>